/************************************************************
 *  * Hyphenate CONFIDENTIAL
 * __________________
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 *
 * NOTICE: All information contained herein is, and remains
 * the property of Hyphenate Inc.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Hyphenate Inc.
 */

#import "ConversationListController.h"

#import "ChatViewController.h"
#import "EMSearchBar.h"
#import "EMSearchDisplayController.h"
#import "RobotManager.h"
#import "RobotChatViewController.h"
#import "UserProfileManager.h"
#import "RealtimeSearchUtil.h"
#import "RedPacketChatViewController.h"
#import "ChatDemoHelper.h"

#import "MainViewController.h"


@implementation EMConversation (search)

//根据用户昵称,环信机器人名称,群名称进行搜索
- (NSString*)showName
{
    if (self.type == EMConversationTypeChat) {
        if ([[RobotManager sharedInstance] isRobotWithUsername:self.conversationId]) {
            return [[RobotManager sharedInstance] getRobotNickWithUsername:self.conversationId];
        }
        return [[UserProfileManager sharedInstance] getNickNameWithUsername:self.conversationId];
    } else if (self.type == EMConversationTypeGroupChat) {
        if ([self.ext objectForKey:@"subject"] || [self.ext objectForKey:@"isPublic"]) {
            return [self.ext objectForKey:@"subject"];
        }
    }
    return self.conversationId;
}

@end

@interface ConversationListController ()<EaseConversationListViewControllerDelegate, EaseConversationListViewControllerDataSource,UISearchDisplayDelegate, UISearchBarDelegate>

@property (nonatomic, strong) UIView *networkStateView;
@property (nonatomic, strong) EMSearchBar           *searchBar;

@property (strong, nonatomic) EMSearchDisplayController *searchController;

@property (strong,nonatomic) UIView *systemView;

@property (nonatomic,strong) UIView * headView;//头部

@end


@implementation ConversationListController

-(UIView *)systemView{
    if (!_systemView) {
        _systemView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, mainScreenSize.width, mainScreenSize.height-114)];
        _systemView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_systemView];
        
        UILabel *headLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, -0.5, mainScreenSize.width, 1)];
        headLabel.backgroundColor = RGB(199, 199, 199);
        [_systemView addSubview:headLabel];
    }
    return _systemView;
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = RGB(249, 249, 249);
    
    [self setupBarButtonItem];
    
    
    self.showRefreshHeader = YES;
    self.delegate = self;
    self.dataSource = self;
    
    [self tableViewDidTriggerHeaderRefresh];
//    
//       self.title = @"个人信息";

    self.tableView.frame = CGRectMake(0, 65, self.view.frame.size.width, self.view.frame.size.height - 65);

    [self networkStateView];
    
//    [self searchController];
     
    [self removeEmptyConversationsFromDB];
    
    UILabel *lineLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, 0.5)];
    lineLabel.backgroundColor = [UIColor grayColor];
    [self.view addSubview:lineLabel];
}

- (void)setupBarButtonItem
{
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 30, 25, 25)];
    [backButton setImage:[UIImage imageNamed:@"xiangyou.png"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [self.view  addSubview:backButton];
    
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(kScreen_Width/2 - 40, 25, 80, 40)];
    title.textAlignment = NSTextAlignmentCenter;
    title.font = [UIFont systemFontOfSize:16];
    title.textColor = RGBJ(77);
    title.text = @"名医咨询";
    [self.view addSubview:title];
    
    
    UILabel *lineLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, 0.5)];
    lineLabel.backgroundColor = [UIColor grayColor];
    [self.view addSubview:lineLabel];
//    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
//    [self.navigationItem setLeftBarButtonItem:backItem];
}

-(void)back{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self refresh];
       [self.navigationController setNavigationBarHidden:YES animated:NO];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)removeEmptyConversationsFromDB
{
    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
    NSMutableArray *needRemoveConversations;
    for (EMConversation *conversation in conversations) {
        if (!conversation.latestMessage || (conversation.type == EMConversationTypeChatRoom)) {
            if (!needRemoveConversations) {
                needRemoveConversations = [[NSMutableArray alloc] initWithCapacity:0];
            }
            
            [needRemoveConversations addObject:conversation];
        }
    }
    
    if (needRemoveConversations && needRemoveConversations.count > 0) {
        [[EMClient sharedClient].chatManager deleteConversations:needRemoveConversations deleteMessages:YES];
    }
}

#pragma mark - getter
- (UIView *)networkStateView
{
    if (_networkStateView == nil) {
        _networkStateView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, self.tableView.frame.size.width, 44)];
        _networkStateView.backgroundColor = [UIColor colorWithRed:255 / 255.0 green:199 / 255.0 blue:199 / 255.0 alpha:0.5];
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, (_networkStateView.frame.size.height - 20) / 2, 20, 20)];
        imageView.image = [UIImage imageNamed:@"messageSendFail"];
        [_networkStateView addSubview:imageView];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(imageView.frame) + 5, 0, _networkStateView.frame.size.width - (CGRectGetMaxX(imageView.frame) + 15), _networkStateView.frame.size.height)];
        label.font = [UIFont systemFontOfSize:15.0];
        label.textColor = [UIColor grayColor];
        label.backgroundColor = [UIColor clearColor];
        label.text = NSLocalizedString(@"network.disconnection", @"Network disconnection");
        [_networkStateView addSubview:label];
    }
    
    return _networkStateView;
}

- (UISearchBar *)searchBar
{
    if (!_searchBar) {
        _searchBar = [[EMSearchBar alloc] initWithFrame: CGRectMake(0, 64, self.view.frame.size.width, 44)];
        _searchBar.delegate = self;
        _searchBar.placeholder = NSLocalizedString(@"search", @"Search");
        _searchBar.backgroundColor = [UIColor colorWithRed:0.747 green:0.756 blue:0.751 alpha:1.000];
    }
    
    return _searchBar;
}

- (UIView *)headView
{
    if (!_headView) {
        _headView = [[UIView alloc]initWithFrame:CGRectMake(0, 20, mainScreenSize.width, 44)];
        UIButton * button1 = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, mainScreenSize.width/2, 44)];
        button1.tag = 101;
        [button1 setTitle:@"我的消息" forState:UIControlStateNormal];
        [button1.titleLabel setFont:[UIFont boldSystemFontOfSize:16]];
        [button1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button1 addTarget:self action:@selector(headViewButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [_headView addSubview:button1];
        
        UIButton * button2 = [[UIButton alloc]initWithFrame:CGRectMake(mainScreenSize.width/2, 0, mainScreenSize.width/2, 44)];
        button2.tag = 102;
        [button2 setTitle:@"系统消息" forState:UIControlStateNormal];
        [button2.titleLabel setFont:[UIFont boldSystemFontOfSize:16]];
        [button2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button2 addTarget:self action:@selector(headViewButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [_headView addSubview:button2];
        
        UILabel * line = [[UILabel alloc]initWithFrame:CGRectMake(mainScreenSize.width/4-45, 42, 90, 2)];
        line.tag = 103;
        [line setBackgroundColor:[UIColor blackColor]];
        [_headView addSubview:line];
    }
    
    return _headView;
}

-(void)headViewButtonClick:(UIButton *)btn{
    UILabel * labe = (UILabel *)[_headView viewWithTag:103];
    CGRect frame =  self.view.frame;
    self.view.frame = frame;
    if (btn.tag==101) {
        [labe setFrame:CGRectMake(mainScreenSize.width/4-45, 42, 90, 2)];
        [self.systemView setHidden:YES];
    }else{
        [self.systemView setHidden:NO];
        [labe setFrame:CGRectMake(mainScreenSize.width*3/4-45, 42, 90, 2)];
    }
}

- (EMSearchDisplayController *)searchController
{
    if (_searchController == nil) {
        _searchController = [[EMSearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];
        _searchController.delegate = self;
        _searchController.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        _searchController.searchResultsTableView.tableFooterView = [[UIView alloc] init];
        
        __weak ConversationListController *weakSelf = self;
        [_searchController setCellForRowAtIndexPathCompletion:^UITableViewCell *(UITableView *tableView, NSIndexPath *indexPath) {
            NSString *CellIdentifier = [EaseConversationCell cellIdentifierWithModel:nil];
            EaseConversationCell *cell = (EaseConversationCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            
            // Configure the cell...
            if (cell == nil) {
                cell = [[EaseConversationCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            }
            
            id<IConversationModel> model = [weakSelf.searchController.resultsSource objectAtIndex:indexPath.row];
            cell.model = model;
            
            cell.detailLabel.attributedText = [weakSelf conversationListViewController:weakSelf latestMessageTitleForConversationModel:model];
            cell.timeLabel.text = [weakSelf conversationListViewController:weakSelf latestMessageTimeForConversationModel:model];
            return cell;
        }];
        
        [_searchController setHeightForRowAtIndexPathCompletion:^CGFloat(UITableView *tableView, NSIndexPath *indexPath) {
            return [EaseConversationCell cellHeightWithModel:nil];
        }];
        
        [_searchController setDidSelectRowAtIndexPathCompletion:^(UITableView *tableView, NSIndexPath *indexPath) {
            [tableView deselectRowAtIndexPath:indexPath animated:YES];
            [weakSelf.searchController.searchBar endEditing:YES];
            id<IConversationModel> model = [weakSelf.searchController.resultsSource objectAtIndex:indexPath.row];
            EMConversation *conversation = model.conversation;
            ChatViewController *chatController;
            if ([[RobotManager sharedInstance] isRobotWithUsername:conversation.conversationId]) {
                chatController = [[RobotChatViewController alloc] initWithConversationChatter:conversation.conversationId conversationType:conversation.type];
                chatController.title = [[RobotManager sharedInstance] getRobotNickWithUsername:conversation.conversationId];
            }else {
#ifdef REDPACKET_AVALABLE
                chatController = [[RedPacketChatViewController alloc]
#else
                                  chatController = [[ChatViewController alloc]
#endif
                                                    initWithConversationChatter:conversation.conversationId conversationType:conversation.type];
                                  chatController.title = [conversation showName];
                                  }
                                  [weakSelf.navigationController pushViewController:chatController animated:YES];
                                  [[NSNotificationCenter defaultCenter] postNotificationName:@"setupUnreadMessageCount" object:nil];
                                  [weakSelf.tableView reloadData];
                                  }];
            }
            
            return _searchController;
        }
         
#pragma mark - EaseConversationListViewControllerDelegate
         
         - (void)conversationListViewController:(EaseConversationListViewController *)conversationListViewController
                                     didSelectConversationModel:(id<IConversationModel>)conversationModel
        {
            if (conversationModel) {
                EMConversation *conversation = conversationModel.conversation;
                if (conversation) {
                    if ([[RobotManager sharedInstance] isRobotWithUsername:conversation.conversationId]) {
                        RobotChatViewController *chatController = [[RobotChatViewController alloc] initWithConversationChatter:conversation.conversationId conversationType:conversation.type];
                        chatController.title = [[RobotManager sharedInstance] getRobotNickWithUsername:conversation.conversationId];
                        [self.navigationController pushViewController:chatController animated:YES];
                    } else {
                             //刷新用户数据
//                            NSString *username = [[EMClient sharedClient] currentUsername];
//                        NSLog(@"----da-username = %@",username);
//                         [self downLoadUserInfo:username];

//                        [self downLoadUserInfo:conversationModel.title];
                        
                        
                        //界面跳转，刷新标题、
                        //                        [self setTitle:conversationModel.title];
                        
                        
                        
                        ChatViewController *chatController = [[ChatViewController alloc] initWithConversationChatter:conversationModel.title conversationType:EMConversationTypeChat];
                        chatController.doctorUsername = conversationModel.title;
                        
                        NSDictionary *peopleInfo = [AppConfig getPeopleInfo:conversationModel.title];
                        NSString *nickName = [NSString stringWithFormat:@"%@",[peopleInfo objectForKey:@"nickname"]];
                        if([AppConfig isNULL:nickName]){
                            chatController.title = conversationModel.title;
                        }else{
                            chatController.title = nickName;
                        }
                        
                        //刷新数据
                        dispatch_async(dispatch_get_global_queue(0, 0),^{
                            //刷新列表未读数据显示
                            [self.tableView reloadData];
                            //刷新APP图标未读数据显示
                            MainViewController *mainVC = [[MainViewController alloc]init];
                            [mainVC setupUnreadMessageCount];
                        });
                        
                        [self.navigationController pushViewController:chatController animated:YES];

                    }
                }
                [[NSNotificationCenter defaultCenter] postNotificationName:@"setupUnreadMessageCount" object:nil];
                
            }
        }
         
         -(void)downLoadUserInfo:(NSString *)loginName{
             NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:loginName,@"hnLoginName", nil];
             AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
             manager.responseSerializer = [AFHTTPResponseSerializer serializer];
             [manager POST:url_UserInfo parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
                 
             } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                 NSError * error;
                 NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
                 [self hideHud];
                 if (error) {
                     NSLog(@"====error1:%@",error);
                     return;
                 }
                 NSLog(@"==dict:%@",data);
                 NSString * code = [NSString stringWithFormat:@"%@",[data objectForKey:@"error"]];
                 if ([code isEqualToString:@"0"]) {
                     NSDictionary *userInfo = [data objectForKey:@"data"];
                     NSString *loginName = [NSString stringWithFormat:@"%@",[userInfo objectForKey:@"hnLoginName"]];
                     if ([AppConfig isNULL:loginName]) {
                         loginName = @"";
                     }
                     NSMutableDictionary *peopleDic = [NSMutableDictionary dictionaryWithObjectsAndKeys:loginName,@"hnLoginName", nil];
                     NSString *head = [NSString stringWithFormat:@"%@",[userInfo objectForKey:@"hnHead"]];
                     if ([AppConfig isNULL:head]) {
                         head = @"";
                     }
                     [peopleDic setObject:head forKey:@"hnHead"];
                     NSString *nickName = [NSString stringWithFormat:@"%@",[userInfo objectForKey:@"hnNickName"]];
                     if ([AppConfig isNULL:nickName]) {
                         nickName = @"";
                     }
                     [peopleDic setObject:nickName forKey:@"hnNickName"];
                     NSLog(@"peopleDic = %@",peopleDic);
                     [AppConfig savePeopleInfo:peopleDic];
                 }else{
                     //            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"message"]];
                     //            [self showHint:info];
                 }
             } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull  error) {
                 NSLog(@"====error:%@",error);
                 [self hideHud];
                 //        [self showHint:@"获取用户信息失败"];
             }];
         }
         
         -(void)setTitle:(NSString *)merchantPhone{
             //刷新加载头像数据
             NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:merchantPhone,@"hnLoginName", nil];
             AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
             manager.responseSerializer = [AFHTTPResponseSerializer serializer];
             [manager POST:url_UserInfo parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
                 
             } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                 NSError * error;
                 NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
                 [self hideHud];
                 if (error) {
                     NSLog(@"====error1:%@",error);
                     return;
                 }
                 NSLog(@"==dict:%@",data);
                 NSString * code = [NSString stringWithFormat:@"%@",[data objectForKey:@"error"]];
                 if ([code isEqualToString:@"0"]) {
                     NSDictionary *userInfo = [data objectForKey:@"data"];
                     ChatViewController *chatController = [[ChatViewController alloc] initWithConversationChatter:merchantPhone conversationType:EMConversationTypeChat];
                     chatController.title = [NSString stringWithFormat:@"%@",[userInfo objectForKey:@"hnNickName"]];
                     
                     //刷新数据
                     dispatch_async(dispatch_get_global_queue(0, 0),^{
                         //刷新列表未读数据显示
                         [self.tableView reloadData];
                         //刷新APP图标未读数据显示
                         MainViewController *mainVC = [[MainViewController alloc]init];
                         [mainVC setupUnreadMessageCount];
                     });
                     
                     [self.navigationController pushViewController:chatController animated:YES];
                 }else{
                     //            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"message"]];
                     //            [self showHint:info];
                 }
             } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull   error) {
                 NSLog(@"====error:%@",error);
                 [self hideHud];
                 //        [self showHint:@"获取用户信息失败"];
             }];
         }
         
         
         
         
#pragma mark - EaseConversationListViewControllerDataSource
         
         - (id<IConversationModel>)conversationListViewController:(EaseConversationListViewController *)conversationListViewController
                                           modelForConversation:(EMConversation *)conversation
        {
            EaseConversationModel *model = [[EaseConversationModel alloc] initWithConversation:conversation];
            if (model.conversation.type == EMConversationTypeChat) {
                if ([[RobotManager sharedInstance] isRobotWithUsername:conversation.conversationId]) {
                    model.title = [[RobotManager sharedInstance] getRobotNickWithUsername:conversation.conversationId];
                } else {
                    UserProfileEntity *profileEntity = [[UserProfileManager sharedInstance] getUserProfileByUsername:conversation.conversationId];
                    if (profileEntity) {
                        model.title = profileEntity.nickname == nil ? profileEntity.username : profileEntity.nickname;
                        model.avatarURLPath = profileEntity.imageUrl;
                    }
                }
            } else if (model.conversation.type == EMConversationTypeGroupChat) {
                NSString *imageName = @"groupPublicHeader";
                if (![conversation.ext objectForKey:@"subject"])
                {
                    NSArray *groupArray = [[EMClient sharedClient].groupManager getAllGroups];
                    for (EMGroup *group in groupArray) {
                        if ([group.groupId isEqualToString:conversation.conversationId]) {
                            NSMutableDictionary *ext = [NSMutableDictionary dictionaryWithDictionary:conversation.ext];
                            [ext setObject:group.subject forKey:@"subject"];
                            [ext setObject:[NSNumber numberWithBool:group.isPublic] forKey:@"isPublic"];
                            conversation.ext = ext;
                            break;
                        }
                    }
                }
                NSDictionary *ext = conversation.ext;
                model.title = [ext objectForKey:@"subject"];
                imageName = [[ext objectForKey:@"isPublic"] boolValue] ? @"groupPublicHeader" : @"groupPrivateHeader";
                model.avatarImage = [UIImage imageNamed:imageName];
            }
            return model;
        }
         
         - (NSAttributedString *)conversationListViewController:(EaseConversationListViewController *)conversationListViewController
                         latestMessageTitleForConversationModel:(id<IConversationModel>)conversationModel
        {
            NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:@""];
            EMMessage *lastMessage = [conversationModel.conversation latestMessage];
            if (lastMessage) {
                NSString *latestMessageTitle = @"";
                EMMessageBody *messageBody = lastMessage.body;
                switch (messageBody.type) {
                    case EMMessageBodyTypeImage:{
                        latestMessageTitle = NSLocalizedString(@"图片", @"[image]");
                    } break;
                    case EMMessageBodyTypeText:{
                        // 表情映射。
                        NSString *didReceiveText = [EaseConvertToCommonEmoticonsHelper
                                                    convertToSystemEmoticons:((EMTextMessageBody *)messageBody).text];
                        latestMessageTitle = didReceiveText;
                        if ([lastMessage.ext objectForKey:MESSAGE_ATTR_IS_BIG_EXPRESSION]) {
                            latestMessageTitle = @"[动画表情]";
                        }
                    } break;
                    case EMMessageBodyTypeVoice:{
                        latestMessageTitle = NSLocalizedString(@"语音消息", @"[voice]");
                    } break;
                    case EMMessageBodyTypeLocation: {
                        latestMessageTitle = NSLocalizedString(@"message.location1", @"[location]");
                    } break;
                    case EMMessageBodyTypeVideo: {
                        latestMessageTitle = NSLocalizedString(@"message.video1", @"[video]");
                    } break;
                    case EMMessageBodyTypeFile: {
                        latestMessageTitle = NSLocalizedString(@"message.file1", @"[file]");
                    } break;
                    default: {
                    } break;
                }
                
                if (lastMessage.direction == EMMessageDirectionReceive) {
                    NSString *from = lastMessage.from;
                    UserProfileEntity *profileEntity = [[UserProfileManager sharedInstance] getUserProfileByUsername:from];
                    if (profileEntity) {
                        from = profileEntity.nickname == nil ? profileEntity.username : profileEntity.nickname;
                    }
                    latestMessageTitle = [NSString stringWithFormat:@"%@: %@", from, latestMessageTitle];
                }
                
                NSDictionary *ext = conversationModel.conversation.ext;
                if (ext && [ext[kHaveUnreadAtMessage] intValue] == kAtAllMessage) {
                    latestMessageTitle = [NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"group.atAll", nil), latestMessageTitle];
                    attributedStr = [[NSMutableAttributedString alloc] initWithString:latestMessageTitle];
                    [attributedStr setAttributes:@{NSForegroundColorAttributeName : [UIColor colorWithRed:1.0 green:.0 blue:.0 alpha:0.5]} range:NSMakeRange(0, NSLocalizedString(@"group.atAll", nil).length)];
                    
                }
                else if (ext && [ext[kHaveUnreadAtMessage] intValue] == kAtYouMessage) {
                    latestMessageTitle = [NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"group.atMe", @"[Somebody @ me]"), latestMessageTitle];
                    attributedStr = [[NSMutableAttributedString alloc] initWithString:latestMessageTitle];
                    [attributedStr setAttributes:@{NSForegroundColorAttributeName : [UIColor colorWithRed:1.0 green:.0 blue:.0 alpha:0.5]} range:NSMakeRange(0, NSLocalizedString(@"group.atMe", @"[Somebody @ me]").length)];
                }
                else {
                    attributedStr = [[NSMutableAttributedString alloc] initWithString:latestMessageTitle];
                }
            }
            
            return attributedStr;
        }
         
         - (NSString *)conversationListViewController:(EaseConversationListViewController *)conversationListViewController
                          latestMessageTimeForConversationModel:(id<IConversationModel>)conversationModel
        {
            NSString *latestMessageTime = @"";
            EMMessage *lastMessage = [conversationModel.conversation latestMessage];;
            if (lastMessage) {
                latestMessageTime = [NSDate formattedTimeFromTimeInterval:lastMessage.timestamp];
            }
            
            
            return latestMessageTime;
        }
         
#pragma mark - UISearchBarDelegate
         
         - (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
        {
            [searchBar setShowsCancelButton:YES animated:YES];
            
            return YES;
        }
         
         - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
        {
            __weak typeof(self) weakSelf = self;
            [[RealtimeSearchUtil currentUtil] realtimeSearchWithSource:self.dataArray searchText:(NSString *)searchText collationStringSelector:@selector(title) resultBlock:^(NSArray *results) {
                if (results) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf.searchController.resultsSource removeAllObjects];
                        [weakSelf.searchController.resultsSource addObjectsFromArray:results];
                        [weakSelf.searchController.searchResultsTableView reloadData];
                    });
                }
            }];
        }
         
         - (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
        {
            return YES;
        }
         
         - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
        {
            [searchBar resignFirstResponder];
        }
         
         - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
        {
            searchBar.text = @"";
            [[RealtimeSearchUtil currentUtil] realtimeSearchStop];
            [searchBar resignFirstResponder];
            [searchBar setShowsCancelButton:NO animated:YES];
        }
         
#pragma mark - public
         
         -(void)refresh
        {
            [self refreshAndSortView];
        }
         
         -(void)refreshDataSource
        {
            [self tableViewDidTriggerHeaderRefresh];
        }
         
         - (void)isConnect:(BOOL)isConnect{
             if (!isConnect) {
                 self.tableView.tableHeaderView = _networkStateView;
             }
             else{
                 self.tableView.tableHeaderView = nil;
             }
             
         }
         
         - (void)networkChanged:(EMConnectionState)connectionState
        {
            if (connectionState == EMConnectionDisconnected) {
                self.tableView.tableHeaderView = _networkStateView;
                self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(65,  self.tableView.frame.size.width, self.tableView.frame.size.height - 115, 60)];
            }
            else{
                self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(65,  self.tableView.frame.size.width, self.tableView.frame.size.height - 115, 60)];
                self.tableView.tableHeaderView = nil;
            }
        }
         
         @end
